package com.efounder.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.TabBottomActivity;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.ospmobilelib.R;
import com.efounder.util.WebViewUtil;
import com.efounder.view.titlebar.AbTitleBar;
import com.pansoft.espcomp.DateWindows;
import com.pansoft.espcomp.DateWindows.DateOnclickListener;
import com.pansoft.espcomp.ESPWebView;
import com.pansoft.espmodel.EFWebNoticationObject;
import com.pansoft.pullrefresh.ui.PullToRefreshBase;
import com.pansoft.pullrefresh.ui.PullToRefreshBase.OnRefreshListener;
import com.pansoft.pullrefresh.ui.PullToRefreshWebView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

public class SimpleWebFragment extends Fragment {

	private static final String TAG = "SimpleWebFragment";
	private StubObject mMenuItem;
	private String titleStr;
//	CustomProgressDialog dialog;
	private View rootView;// 缓存Fragment view
	AbTitleBar title ;
    private PullToRefreshWebView mPullWebView;
    private WebView mWebView;
	Boolean isShowBottom;
	private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");

	public SimpleWebFragment(StubObject menuItem,String title) {
		this.mMenuItem = menuItem;
		this.titleStr = title;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
		

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	/*	TabBottomActivity menuFrag = TabBottomActivity.getInstance();
        isShowBottom = (menuFrag.getBottomBar().getVisibility()==View.VISIBLE);
		if(isShowBottom)
		menuFrag.getBottomBar().setVisibility(View.GONE);*/
	}


	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	/*	if(isShowBottom){
			TabBottomActivity menuFrag = TabBottomActivity.getInstance();
			menuFrag.getBottomBar().setVisibility(View.VISIBLE);
			}*/
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.test_webview, container, false);

		Hashtable menuTable = mMenuItem.getStubTable();
		String webUrl = (String) menuTable.get("url");
		String param = (String) menuTable.get("param");
		String value = (String) menuTable.get("value");
		String titleName = (String)menuTable.get("caption");
		
		
		RelativeLayout include = (RelativeLayout) rootView.findViewById(R.id.include);
		TextView title = (TextView)rootView.findViewById(R.id.fragmenttitle);
		title.setText(titleName);
		LinearLayout leftbacklayout = (LinearLayout) rootView.findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
	

		leftbacklayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 SimpleWebFragment.this.getFragmentManager().popBackStack();
			}
		});
		
		
		Button buttonRight = (Button) rootView.findViewById(R.id.closeButton);
		buttonRight.setVisibility(View.INVISIBLE);
		buttonRight.setBackgroundResource(R.drawable.rightmenu);
		buttonRight.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//web.loadUrl("www.baidu.com");
				//new MonthWindows(SimpleWebFragment.this.getActivity(), v);
			final DateWindows dateWindows = 	new DateWindows(SimpleWebFragment.this.getActivity(), v);
			dateWindows.setDateOnclickListener(new DateOnclickListener() {
				
				@Override
				public void ondateCalendarClick(String date) {
					// TODO Auto-generated method stub
					dateWindows.dismiss();
					//web.loadUrl("http://www.baidu.com");
					String[] param = new String[1];
					param[0]=date;
					sendBroadCast("date",param);
					
				}
			});
			}
		});
		
		

		final String url = String.valueOf(webUrl);
		mPullWebView = (PullToRefreshWebView) rootView.findViewById(R.id.mywebview);;
		mWebView = mPullWebView.getRefreshableView();
		OnRefreshListener<ESPWebView> listner =	new OnRefreshListener<ESPWebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ESPWebView> refreshView) {
				// TODO Auto-generated method stub
				mWebView.loadUrl(url);
			}
			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ESPWebView> refreshView) {
				// TODO Auto-generated method stub
				
			}
		};
		mPullWebView.setOnRefreshListener(listner);
		
		//添加webview重定向和加载的控制函数
		mWebView.setWebViewClient(new WebViewClient() {
		    @Override
		    public boolean shouldOverrideUrlLoading(WebView view, String url) {
		    	//reload回调
		    	if(url.contains("esp")){
					/*Toast.makeText(getApplicationContext(), "默认Toast样式",
			    		     Toast.LENGTH_SHORT).show();*/
					WebViewUtil.openEspUrl(url);
				}else{
					mWebView.loadUrl(url);
				}
		    	//////////////loadInterface.Reload(url);
		    	//progressBar = ProgressDialog.show(espContext, "MaxPowerSoft Example", "Loading...");  
		        return true;
		    }
		    @Override
		    public void onPageStarted(WebView view, String url, Bitmap favicon) {

		        super.onPageStarted(view, url, favicon);
		        //load回调
		    	//LoadingDataUtil.show();
		       // progressBar = ProgressDialog.show(espContext, "MaxPowerSoft Example", "Loading...");  
		       ////////// loadInterface.load(url);
		    	//ESPWebView.this.loadUrl(url);
		    }
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				/*if (progressBar.isShowing()) {  
	                progressBar.dismiss();  
	            }  */
			//	LoadingDataUtil.dismiss();
				mPullWebView.onPullDownRefreshComplete();
	            setLastUpdateTime();
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				//LoadingDataUtil.dismiss();
			}
		    

			public void onReceivedSslError(WebView view, SslErrorHandler handler,
					SslError error) {
				// handler.cancel(); 默认的处理方式，WebView变成空白页
				handler.proceed();// 接受证书
				//LoadingDataUtil.dismiss();
				// handleMessage(Message msg); 其他处理k
			}
		});
		 setLastUpdateTime();
		System.out.println(String.valueOf(webUrl));
		mWebView.loadUrl(String.valueOf(webUrl));
		return rootView;
	}

	  private void setLastUpdateTime() {
	        String text = formatDateTime(System.currentTimeMillis());
	        mPullWebView.setLastUpdatedLabel(text);
	    }
	   private String formatDateTime(long time) {
	        if (0 == time) {
	            return "";
	        }
	        
	        return mDateFormat.format(new Date(time));
	    }
	@Override
	public void onStart() {
		title = ((TabBottomActivity)getActivity()).getTitleBar();
		title.setTitleText(titleStr);
		title.setVisibility(View.GONE);
		super.onStart();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BroadCastutil.getinstance().unregisterWebBroadcastList((Context)SimpleWebFragment.this.getActivity());
	}
	
	/*
	 * 文件保存成功后发送广播
	 */
	public void sendBroadCast(String type,String[] parm) {

		String ACTION = "webView";
		Intent intent = new Intent();
		EFWebNoticationObject efWebNoticationObject = new  EFWebNoticationObject();
		efWebNoticationObject.setType("date");
		efWebNoticationObject.setParam(parm);
		intent.putExtra("name", efWebNoticationObject);
		intent.setAction(ACTION);
		// 普通广播
		SimpleWebFragment.this.getActivity().sendBroadcast(intent);
	}
	
}
